import React, { Component, Suspense } from "react";
import { connect } from "dva";
import {
	Drawer,
	Form,
	Button,
	Col,
	Row,
	Input,
	Select,
	DatePicker,
	Icon,
	message,
	Pagination,
} from "antd";
import styles from "./typeNode.less";
import UserSession from "@/UserSession";

const { Option } = Select;
const Search = Input.Search;

class SimilarQuestion extends Component {
	constructor(props) {
		super(props);

		this.state = {
			similarQuestions: props.similarQuestions,
			similarQuestion: "",
			questionIndex: null,
			showPagenation: false,
			moreQuestionList: [],
			moreQuestionPage: 1,
			searchText: "",
		};
	}

	componentDidMount() {
		this.props.onRef(this);
		if (this.props.similarQuestions) {
			this.setState({ similarQuestions: this.props.similarQuestions });
		}
		if (this.props.isTowDrawer && this.props.similarQuestions) {
			this.setState({ moreQuestionList: this.props.similarQuestions });
		}
	}
	componentWillReceiveProps() {
		if (this.props.similarQuestions) {
			this.setState({ similarQuestions: this.props.similarQuestions });
		}
	}

	addQuestion = (e) => {
		e.preventDefault();
		e.persist();
		const { isGuid } = this.props;
		var reg = new RegExp("^[ ]+$");
		if (!e.target.value) {
			if (isGuid) {
				message.error("同义词不可为空");
			} else {
				message.error("问题不可为空");
			}

			return false;
		}

		if (reg.test(e.target.value)) {
			if (isGuid) {
				message.error("同义词不可为空");
			} else {
				message.error("问题不可为空");
			}
			return false;
		}
		let flog = true;
		const val = e.target.value;
		const that = this;
		let { moreQuestionList, similarQuestions } = this.state;
		if (that.props.isTowDrawer) {
			flog = moreQuestionList.some((q) => {
				if (q == val) {
					return true;
				}
			});
		} else {
			flog = similarQuestions.some((q) => {
				if (q == val) {
					return true;
				}
			});
		}
		if (flog) {
			message.info("【" + e.target.value + "】问题已存在");
			return false;
		}
		that.setState(
			{
				similarQuestion: "",
			},
			() => {
				if (that.props.isTowDrawer) {
					this.setState({
						moreQuestionList: [val, ...moreQuestionList],
					});
				} else {
					that.props.addQuestion(val);
				}
			}
		);
	};

	fixQuestion = (e) => {
		this.setState({ similarQuestion: e.target.value });
	};

	remove = (index, e) => {
		if (this.props.isTowDrawer) {
			let { moreQuestionList } = this.state;
			moreQuestionList = moreQuestionList.filter((key) => key !== e);
			this.setState({ moreQuestionList });
		} else {
			this.props.remove(index, e);
		}
	};

	changeIndex = (index) => {
		if (index === 0) {
			message.info("已经是第一位");
			return;
		}
		if (this.props.isTowDrawer) {
			let { moreQuestionList } = this.state;
			moreQuestionList[index - 1] = moreQuestionList.splice(
				index,
				1,
				moreQuestionList[index - 1]
			)[0];
			this.setState({ moreQuestionList });
		} else {
			this.props.changeIndex(index);
		}
	};
	addIcon() {
		const { isGuid } = this.props;
		if (this.state.similarQuestion === "") {
			if (isGuid) {
				message.error("同义词不可为空");
			} else {
				message.error("问题不可为空");
			}
			return false;
		}
		let val = this.state.similarQuestion;
		const that = this;
		let { moreQuestionList, similarQuestions } = that.state;
		let flog = true;
		if (that.props.isTowDrawer) {
			flog = moreQuestionList.some((q) => {
				if (q == val) {
					return true;
				}
			});
		} else {
			flog = similarQuestions.some((q) => {
				if (q == val) {
					return true;
				}
			});
		}
		if (flog) {
			message.info("【" + val + "】问题已存在");
			return false;
		}
		this.setState(
			{
				similarQuestion: "",
			},
			() => {
				if (that.props.isTowDrawer) {
					this.setState({
						moreQuestionList: [val, ...moreQuestionList],
					});
				} else {
					that.props.addQuestion(val);
				}
			}
		);
	}
	changeSimilarItem(e, index, originVal) {
		let val = e.target.value;
		let data = { val, index };
		if (this.props.isTowDrawer) {
			let { moreQuestionList, searchText } = this.state;
			let originIndex = 0;
			if (searchText) {
				moreQuestionList.map((item, nowIndex) => {
					if (item == originVal) {
						originIndex = nowIndex;
					}
				});
				moreQuestionList[originIndex] = val;
			} else {
				moreQuestionList[index] = val;
			}
			this.setState({
				moreQuestionList,
			});
		} else {
			this.props.changeSimilarItem(data);
		}
	}
	setQusSlot = (e, val) => {
		const { isShowQusSlot } = this.state;
		const { slotList, knowledgeType } = this.props;
		// isShowQusSlot === 'sm' && slotList && knowledgeType
		this.setState(
			{
				isShowQusSlot: e,
				oldQus: val.target.value,
			},
			() => {}
		);
	};
	addSlotToQuestion = (val, index) => {
		const value = `${this.state.similarQuestion}<${val}>`;
		this.similarInput.focus();
		this.setState({
			similarQuestion: value,
		});
	};
	showQuestionSlot = (e, index) => {
		this.setState({
			questionIndex: index,
			oldQus: e.target.value,
		});
	};
	addSlotToSmQuestion = (name, index) => {
		const resemblanceX = `resemblance${index}`;
		this.refs[resemblanceX].focus();
		const { similarQuestions } = this.props;
		const value = `${similarQuestions[index]}<${name}>`;
		let data = { value, index };
		this.props.addSlotToSmQuestion(data);
	};
	moreQuestions() {
		this.setState({ showPagenation: true });
	}
	seeMore = () => {
		this.props.seeMore(true);
	};
	getQusBySearch(val) {
		this.setState({
			searchText: val,
			moreQuestionPage: 1,
		});
	}
	pageQuestion = (page) => {
		this.setState({
			moreQuestionPage: page,
		});
	};
	doSearch = () => {
		let { moreQuestionList, searchText } = this.state;
		return moreQuestionList.filter((r) => r.indexOf(searchText) > -1);
	};
	render() {
		const { getFieldDecorator } = this.props.form;
		let {
			similarQuestion,
			isShowQusSlot,
			showMore,
			showPagenation,
			moreQuestionList,
			moreQuestionPage,
			searchText,
		} = this.state;
		const {
			slotList,
			isShowMore,
			isTowDrawer,
			similarQuestions,
			keys,
			knowledgeType,
			isGuid,
		} = this.props;
		let minIndex = (moreQuestionPage - 1) * 10;
		let maxIndex = (moreQuestionPage - 1) * 10 + 10;
		if (searchText) {
			moreQuestionList = this.doSearch();
		}
		const formItemLayout = {
			labelCol: {
				xs: { span: 26 },
				sm: { span: keys == 1 ? 4 : 2 },
			},
			wrapperCol: {
				xs: { span: 22 },
				sm: { span: 20 },
			},
		};
		const formItemLayoutWithOutLabel = {
			wrapperCol: {
				xs: { span: 22, offset: 4 },
				sm: { span: 20, offset: keys == 1 ? 4 : 2 },
			},
		};
		return (
			<div>
				{!isTowDrawer ? (
					""
				) : (
					<div style={{ paddingLeft: 51, marginBottom: 10, textAlign: "left" }}>
						<Search
							placeholder={isGuid ? "请输入同义词" : "请输入关键字"}
							style={{ width: 300, marginLeft: 10 }}
							onSearch={(value) => {
								this.getQusBySearch(value);
							}}
						/>
					</div>
				)}
				<Form.Item label={isGuid ? "同义词" : "相似问"} {...formItemLayout}>
					<Row>
						<Col span={21}>
							<Input
								value={this.state.similarQuestion}
								className={styles.inputItem}
								onChange={(e) => this.fixQuestion(e)}
								placeholder={
									isGuid
										? "请输入同义词，点击回车键继续添加"
										: "请输入相似问题，点击回车键继续添加"
								}
								ref={(input) => {
									this.similarInput = input;
								}}
								onPressEnter={(e) => this.addQuestion(e, false)}
								onFocus={(e) => this.setQusSlot("sm", e)}
								disabled={!UserSession.isSystemKnowledge() ? false : true}
							/>
							<span>
								{isShowQusSlot === "sm" && slotList && knowledgeType === 1
									? slotList.map((slotItem, index) => {
											return (
												<Button
													key={index}
													htmlType='button'
													size='small'
													style={{ marginRight: 10 }}
													onClick={() =>
														this.addSlotToQuestion(slotItem.name, "")
													}>
													&lt;{slotItem.name}&gt;
												</Button>
											);
									  })
									: ""}
							</span>
						</Col>
						<Col span={3}>
							<Icon
								type='plus-circle'
								style={{
									fontSize: 20,
									marginLeft: 10,
									cursor: "pointer",
									marginTop: 5,
								}}
								onClick={(e) => this.addIcon()}
							/>
						</Col>
					</Row>
				</Form.Item>
				{isTowDrawer
					? moreQuestionList.map((item, index) =>
							(index > minIndex || index === minIndex) && index < maxIndex ? (
								<Form.Item {...formItemLayoutWithOutLabel} key={index}>
									<div>
										<Input
											value={item}
											key={index}
											style={{ width: "88%" }}
											placeholder={isGuid ? "请输入同义词" : "请输入相似问题"}
											ref={`resemblance${index}`}
											className={styles.inputItem}
											onChange={(e) => this.changeSimilarItem(e, index, item)}
											onFocus={(e) => this.showQuestionSlot(e, index)}
										/>
										<span>
											<Icon
												className='dynamic-delete-button'
												type='close-circle'
												onClick={() => this.remove(index, item)}
												style={{
													fontSize: 20,
													marginLeft: 10,
													cursor: "pointer",
													marginTop: 5,
												}}
											/>
											{searchText != "" ? (
												""
											) : (
												<Icon
													type='arrow-up'
													onClick={() => this.changeIndex(index)}
													style={{
														fontSize: 20,
														marginLeft: 10,
														cursor: "pointer",
														marginTop: 5,
													}}
												/>
											)}
										</span>
									</div>
								</Form.Item>
							) : (
								""
							)
					  )
					: similarQuestions.map((sm, index) =>
							index < 6 && index > -1 ? (
								<Form.Item {...formItemLayoutWithOutLabel} key={index}>
									<div>
										<Input
											value={sm}
											key={index}
											style={{ width: "88%" }}
											placeholder={isGuid ? "请输入同义词" : "请输入相似问题"}
											ref={`resemblance${index}`}
											className={styles.inputItem}
											onChange={(e) => this.changeSimilarItem(e, index)}
											onFocus={(e) => this.showQuestionSlot(e, index)}
											disabled={!UserSession.isSystemKnowledge() ? false : true}
										/>
										{!UserSession.isSystemKnowledge() ? (
											<span>
												<Icon
													className='dynamic-delete-button'
													type='close-circle'
													onClick={() => this.remove(index, sm)}
													style={{
														fontSize: 20,
														marginLeft: 10,
														cursor: "pointer",
														marginTop: 5,
													}}
												/>
												<Icon
													type='arrow-up'
													onClick={() => this.changeIndex(index)}
													style={{
														fontSize: 20,
														marginLeft: 10,
														cursor: "pointer",
														marginTop: 5,
													}}
												/>
											</span>
										) : null}
									</div>
									{index === this.state.questionIndex &&
									slotList &&
									knowledgeType === 1 ? (
										<div>
											{slotList.map((slotItem, i) => {
												return (
													<Button
														key={i}
														htmlType='button'
														size='small'
														style={{ marginRight: 10 }}
														onClick={() =>
															this.addSlotToSmQuestion(slotItem.name, index)
														}>
														&lt;{slotItem.name}&gt;
													</Button>
												);
											})}
										</div>
									) : null}
								</Form.Item>
							) : (
								""
							)
					  )}
				{isTowDrawer ? (
					<Pagination
						defaultCurrent={1}
						style={{ textAlign: "center" }}
						total={moreQuestionList.length}
						current={moreQuestionPage}
						onChange={(pageNumber) => this.pageQuestion(pageNumber)}
					/>
				) : (
					""
				)}
				{isShowMore ? (
					<Form.Item {...formItemLayoutWithOutLabel}>
						<Button htmlType='button' onClick={() => this.seeMore()}>
							{isGuid ? "更多同义词" : "更多相似问题"}
						</Button>
					</Form.Item>
				) : (
					""
				)}
			</div>
		);
	}
}

export default Form.create()(SimilarQuestion);
